<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />









  <meta name="baidu-site-verification" content="Q7ugSRSO7V" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Hexo, NexT" />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="int int64 string之间转换#string到int  int,err:=strconv.Atoi(string)  #string到int64  int64, err := strconv.ParseInt(string, 10, 64)  #int到string  string:=strconv.Itoa(int)  #int64到string  string:=strconv.Fo">
<meta property="og:type" content="article">
<meta property="og:title" content="数据类型判断与转换">
<meta property="og:url" content="http://yoursite.com/golang/数据类型判断与转换/index.html">
<meta property="og:site_name" content="chimps">
<meta property="og:description" content="int int64 string之间转换#string到int  int,err:=strconv.Atoi(string)  #string到int64  int64, err := strconv.ParseInt(string, 10, 64)  #int到string  string:=strconv.Itoa(int)  #int64到string  string:=strconv.Fo">
<meta property="og:updated_time" content="2017-04-23T13:42:26.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="数据类型判断与转换">
<meta name="twitter:description" content="int int64 string之间转换#string到int  int,err:=strconv.Atoi(string)  #string到int64  int64, err := strconv.ParseInt(string, 10, 64)  #int到string  string:=strconv.Itoa(int)  #int64到string  string:=strconv.Fo">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"hide","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":30},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/golang/数据类型判断与转换/"/>





  <title> 数据类型判断与转换 | chimps </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?dcb994042608bdb310eff950ba755ff1";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">chimps</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/golang/数据类型判断与转换/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="chimps">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://sfault-avatar.b0.upaiyun.com/416/326/4163260007-58a1621e63a68_huge256">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="chimps">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                数据类型判断与转换
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-04-23T21:42:26+08:00">
                2017-04-23
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/golang/" itemprop="url" rel="index">
                    <span itemprop="name">golang</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a class="cloud-tie-join-count" href="/golang/数据类型判断与转换/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count join-count" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="int-int64-string之间转换"><a href="#int-int64-string之间转换" class="headerlink" title="int int64 string之间转换"></a>int int64 string之间转换</h1><figure class="highlight go"><table><tr><td class="code"><pre><div class="line">#<span class="keyword">string</span>到<span class="keyword">int</span>  </div><div class="line"><span class="keyword">int</span>,err:=strconv.Atoi(<span class="keyword">string</span>)  </div><div class="line">#<span class="keyword">string</span>到<span class="keyword">int64</span>  </div><div class="line"><span class="keyword">int64</span>, err := strconv.ParseInt(<span class="keyword">string</span>, <span class="number">10</span>, <span class="number">64</span>)  </div><div class="line">#<span class="keyword">int</span>到<span class="keyword">string</span>  </div><div class="line"><span class="keyword">string</span>:=strconv.Itoa(<span class="keyword">int</span>)  </div><div class="line">#<span class="keyword">int64</span>到<span class="keyword">string</span>  </div><div class="line"><span class="keyword">string</span>:=strconv.FormatInt(<span class="keyword">int64</span>,<span class="number">10</span>)</div></pre></td></tr></table></figure>
<h1 id="断言"><a href="#断言" class="headerlink" title="断言"></a>断言</h1><p>Go语言里面有一个语法，可以直接判断是否是该类型的变量： <code>value, ok = element.(T)</code>，这里value就是变量的值，ok是一个bool类型，element是interface变量，T是断言的类型。<br>　　如果element里面确实存储了T类型的数值，那么ok返回true，否则返回false。</p>
<ul>
<li><p>demo1</p>
<figure class="highlight go"><table><tr><td class="code"><pre><div class="line"><span class="keyword">var</span> a <span class="keyword">interface</span>&#123;&#125;</div><div class="line">a = <span class="string">"zhangsan"</span></div><div class="line"><span class="comment">// interface&#123;&#125; =&gt; string (断言)</span></div><div class="line">a = a.(<span class="keyword">string</span>)</div><div class="line"><span class="comment">// 如果直接string(a), 则报错:</span></div><div class="line">cannot convert a (<span class="keyword">type</span> <span class="keyword">interface</span> &#123;&#125;) to <span class="keyword">type</span> <span class="keyword">string</span>: need <span class="keyword">type</span> assertion</div></pre></td></tr></table></figure>
</li>
<li><p>demo2</p>
<figure class="highlight go"><table><tr><td class="code"><pre><div class="line"><span class="keyword">package</span> main</div><div class="line"></div><div class="line"><span class="keyword">import</span> (</div><div class="line">    <span class="string">"fmt"</span></div><div class="line">    <span class="string">"strconv"</span></div><div class="line">)</div><div class="line"></div><div class="line"><span class="keyword">type</span> Element <span class="keyword">interface</span>&#123;&#125;</div><div class="line"><span class="keyword">type</span> List [] Element</div><div class="line"></div><div class="line"><span class="keyword">type</span> Person <span class="keyword">struct</span> &#123;</div><div class="line">    name <span class="keyword">string</span></div><div class="line">    age <span class="keyword">int</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">//定义了String方法，实现了fmt.Stringer</span></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="params">(p Person)</span> <span class="title">String</span><span class="params">()</span> <span class="title">string</span></span> &#123;</div><div class="line">    <span class="keyword">return</span> <span class="string">"(name: "</span> + p.name + <span class="string">" - age: "</span>+strconv.Itoa(p.age)+ <span class="string">" years)"</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</div><div class="line">    list := <span class="built_in">make</span>(List, <span class="number">3</span>)</div><div class="line">    list[<span class="number">0</span>] = <span class="number">1</span> <span class="comment">// an int</span></div><div class="line">    list[<span class="number">1</span>] = <span class="string">"Hello"</span> <span class="comment">// a string</span></div><div class="line">    list[<span class="number">2</span>] = Person&#123;<span class="string">"Dennis"</span>, <span class="number">70</span>&#125;</div><div class="line"></div><div class="line">    <span class="keyword">for</span> index, element := <span class="keyword">range</span> list &#123;</div><div class="line">        <span class="keyword">if</span> value, ok := element.(<span class="keyword">int</span>); ok &#123;</div><div class="line">            fmt.Printf(<span class="string">"list[%d] is an int and its value is %d\n"</span>, index, value)</div><div class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> value, ok := element.(<span class="keyword">string</span>); ok &#123;</div><div class="line">            fmt.Printf(<span class="string">"list[%d] is a string and its value is %s\n"</span>, index, value)</div><div class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> value, ok := element.(Person); ok &#123;</div><div class="line">            fmt.Printf(<span class="string">"list[%d] is a Person and its value is %s\n"</span>, index, value)</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            fmt.Println(<span class="string">"list[%d] is of a different type"</span>, index)</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
</ul>
<p><strong>switch测试</strong><br><figure class="highlight go"><table><tr><td class="code"><pre><div class="line"><span class="keyword">package</span> main</div><div class="line"></div><div class="line"><span class="keyword">import</span> (</div><div class="line">    <span class="string">"fmt"</span></div><div class="line">    <span class="string">"strconv"</span></div><div class="line">)</div><div class="line"></div><div class="line"><span class="keyword">type</span> Element <span class="keyword">interface</span>&#123;&#125;</div><div class="line"><span class="keyword">type</span> List [] Element</div><div class="line"></div><div class="line"><span class="keyword">type</span> Person <span class="keyword">struct</span> &#123;</div><div class="line">    name <span class="keyword">string</span></div><div class="line">    age <span class="keyword">int</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">//打印</span></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="params">(p Person)</span> <span class="title">String</span><span class="params">()</span> <span class="title">string</span></span> &#123;</div><div class="line">    <span class="keyword">return</span> <span class="string">"(name: "</span> + p.name + <span class="string">" - age: "</span>+strconv.Itoa(p.age)+ <span class="string">" years)"</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</div><div class="line">    list := <span class="built_in">make</span>(List, <span class="number">3</span>)</div><div class="line">    list[<span class="number">0</span>] = <span class="number">1</span> <span class="comment">//an int</span></div><div class="line">    list[<span class="number">1</span>] = <span class="string">"Hello"</span> <span class="comment">//a string</span></div><div class="line">    list[<span class="number">2</span>] = Person&#123;<span class="string">"Dennis"</span>, <span class="number">70</span>&#125;</div><div class="line"></div><div class="line">    <span class="keyword">for</span> index, element := <span class="keyword">range</span> list&#123;</div><div class="line">        <span class="keyword">switch</span> value := element.(<span class="keyword">type</span>) &#123;</div><div class="line">            <span class="keyword">case</span> <span class="keyword">int</span>:</div><div class="line">                fmt.Printf(<span class="string">"list[%d] is an int and its value is %d\n"</span>, index, value)</div><div class="line">            <span class="keyword">case</span> <span class="keyword">string</span>:</div><div class="line">                fmt.Printf(<span class="string">"list[%d] is a string and its value is %s\n"</span>, index, value)</div><div class="line">            <span class="keyword">case</span> Person:</div><div class="line">                fmt.Printf(<span class="string">"list[%d] is a Person and its value is %s\n"</span>, index, value)</div><div class="line">            <span class="keyword">default</span>:</div><div class="line">                fmt.Println(<span class="string">"list[%d] is of a different type"</span>, index)</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p><strong>这里有一点需要强调的是：element.(type)语法不能在switch外的任何逻辑里面使用，如果你要在switch外面判断一个类型就使用comma-ok</strong>。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/golang/数组与切片/" rel="next" title="数组与切片">
                <i class="fa fa-chevron-left"></i> 数组与切片
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/golang/文件/" rel="prev" title="文件处理">
                文件处理 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="cloud-tie-wrapper" class="cloud-tie-wrapper"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="https://sfault-avatar.b0.upaiyun.com/416/326/4163260007-58a1621e63a68_huge256"
               alt="chimps" />
          <p class="site-author-name" itemprop="name">chimps</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">59</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">12</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">19</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#int-int64-string之间转换"><span class="nav-number">1.</span> <span class="nav-text">int int64 string之间转换</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#断言"><span class="nav-number">2.</span> <span class="nav-text">断言</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">chimps</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  








  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  


  




	





  
    
    <script>
      var cloudTieConfig = {
        url: document.location.href, 
        sourceId: "",
        productKey: "48bb30d8783d4b38ba0c95e0283238ca",
        target: "cloud-tie-wrapper"
      };
    </script>
    <script src="https://img1.ws.126.net/f2e/tie/yun/sdk/loader.js"></script>
  










  





  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  

</body>
</html>
